var Kuo_admin={
    MULU:"/etc/nginx/default.d/",

    $DATA:{
        code:0,
        data:null,
        msg:"",
        token:""
    },InStall:async function( PREFIX ){
        if(!PREFIX || PREFIX == ""){
            PREFIX = MYSQLconfig.prefix;
        }
        let $db = await db("features");
        let $fan = await $db.Where({'pluginid':"host"}).Find();
       
        if($fan){
            return "已经安装" ;
        }
        let $sql = "INSERT INTO `"+PREFIX+"features` VALUES (2, 'host', '', 'layui-icon-website', '网站管理', '网站管理系统', '阔软工作室', 'https://www.kuosoft.com/', '1', 1, '', 1636519301, '', '', '{\"用户ip\":{\"0\":\"%\"}}', 0, '', '{\"admin_host\":{\"name\":\"网站管理\",\"typeico\":\"layui-icon-console\",\"link\":\"\"},\"admin_shuju\":{\"name\":\"数据管理\",\"typeico\":\"layui-icon-table\",\"link\":\"\"}}', 0);";
        $fan = await $db.Qurey($sql,[]);
        let $sql_ ={};
        $sql_[1]= "CREATE TABLE `"+PREFIX+"host_list` (  `id` bigint unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(50) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '网站名称',  `host` varchar(500) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '网站域名',  `file` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '网站目录',  `part` int unsigned DEFAULT '0' COMMENT '代理端口', `proxy` text COLLATE utf8mb4_general_ci COMMENT '二级目录',  `type` tinyint unsigned DEFAULT '0' COMMENT '类型',  `zip` varchar(255) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '网站代码',  `shell` text COLLATE utf8mb4_general_ci COMMENT '执行脚本',  `pem` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'ssl证书',  `key` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'ssl密钥',  `atime` int unsigned DEFAULT '0' COMMENT '修改日期',  `off` tinyint unsigned DEFAULT '0' COMMENT '开关',  PRIMARY KEY (`id`),  UNIQUE KEY `name` (`name`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";

        $sql_[2]= "CREATE TABLE `"+PREFIX+"host_shuju` (  `id` bigint unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '数据库',  `zhanghao` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '账号',  `pass` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '密码',  `daoru` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '导入文件',  `daochu` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '备份文件',  `atime` int unsigned DEFAULT '0',  `zhixing` varchar(500) COLLATE utf8mb4_general_ci DEFAULT '' COMMENT '执行sql',  PRIMARY KEY (`id`),  KEY `name` (`name`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;";

        for(var iii in $sql_){
            await $db.Qurey($sql_[iii],[]);
        }
    
        if($fan  && $fan .affectedRows > 0){
            
            return true;
        }
        return false;
        
    },SQldaoRu:async function($ID,$_POST){
       
        let $db = await db('host_shuju');
        let DATA = await  $db.Where({id:$ID}).Find();
        if(DATA){
            var exec = require('child_process').exec;
            if(DATA.daoru != ""){
                DATA.daoru = Mode("Tools").GUoLV(DATA.daoru);
                let sqlfile = DIR+'www'+DATA.daoru;
                let zhixing = "mysql -u"+DATA.zhanghao+" -p"+DATA.pass+" -h"+MYSQLconfig.host+" -P"+MYSQLconfig.port+" "+DATA.name+" < "+sqlfile;
                exec(zhixing,function(err,stdout,stderr){
                    try {
                        FS.unlinkSync(sqlfile);  
                    } catch (error) {}

                });
            }
           
            if($_POST && $_POST['zhixing'] && $_POST['zhixing'] != ""){
                let sqlfile = DIR+"temp/" +Mode("Tools").Uuid()+'.sql';
                try { 
                    FS.writeFileSync( sqlfile,$_POST['zhixing'] );
                } catch (error) {}
                let zhixing = "mysql -u"+DATA.zhanghao+" -p"+DATA.pass+" -h"+MYSQLconfig.host+" -P"+MYSQLconfig.port+" "+DATA.name+" < "+sqlfile;
                exec(zhixing,function(err,stdout,stderr){
                    try {
                        FS.unlinkSync(sqlfile);  
                    } catch (error) {}

                });
                
               
            }
            $db.Where({id:$ID}).Update({daoru:"",zhixing:"",atime:Mode("Tools").Time()});
        }



    },AddHost:async function($ID){
   
        let $db = await db('host_list');
        let DATA = await  $db.Where({id:$ID}).Find();
        if(DATA){

            if(DATA.off == 1){
                DATA.file = Trim( Mode("Tools").GUoLV(DATA.file),'/');
                if(DATA.file != ""){
                    
                    if( DATA.part > 0){
                        let lujing = DIR+"HOST/"+DATA.file+'/www/';
                        MkDirs(lujing);
                        var nginx = `
                            server {
                                listen 80;
                                server_name `+str_replace(',',' ',DATA.host)+`;
                                root `+lujing+`;
                                index index.html index.htm index.php;
                            `;
                          
                        if(DATA.pem != "" && DATA.key != ""){
                            nginx +=  `
                            listen 443 ssl;
                            ssl_certificate `+DIR+'www'+DATA.pem+`;
                            ssl_certificate_key `+DIR+'www'+DATA.key+`;
                            ssl_session_timeout 5m;
                            ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
                            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
                            ssl_prefer_server_ciphers on;
                            `;
                        }

                            nginx += `
                            location  ^/(Tpl|attachment|favicon.ico)  {
                                root `+lujing+`;
                                index index.html index.htm index.php;
                            }`;

                        if(DATA.type ==1){
                            nginx += `
                            location / {  
                                proxy_pass http://127.0.0.1:`+DATA.part+`/;  
                                proxy_set_header Host $host:$server_port;  
                            } `;


                        }else if(DATA.type == 2){

                            nginx +=` 

                            location ~ [^/]\.php(/|$)
                            {
                                try_files $uri = 404;
                                fastcgi_pass  127.0.0.1:9000;
                                fastcgi_index index.php;
                                include fastcgi.conf;
                                set $real_script_name $fastcgi_script_name;
                                if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
                                        set $real_script_name $1;
                                        set $path_info $2;
                                }
                                fastcgi_param SCRIPT_FILENAME $document_root$real_script_name;
                                fastcgi_param SCRIPT_NAME $real_script_name;
                                fastcgi_param PATH_INFO $path_info;
                            }
                            `;

                        }else{
                            nginx += `
                            location / {  
                                root `+lujing+`;
                                index index.html index.htm;
                            } `;
                        }

                        if( DATA.proxy && DATA.proxy != "" ){
                            let jiekai =  DATA.proxy .split(",");
                            if(jiekai){
                                for(var xx in  jiekai){
                                    let jiekai_ = jiekai[xx].split('@');
                                    if(jiekai_ && jiekai_.length > 1){

                                        nginx += `
                                        location /`+jiekai_[0]+` {  
                                            proxy_pass http://127.0.0.1:`+jiekai_[1]+`/;  
                                            proxy_set_header Host $host:$server_port;  
                                        } `;
                                    }
                                }
                            }
                        }

                        nginx += `  
                        } 
                        `;
                       try { 
                           FS.writeFileSync( this.MULU+$ID+'.conf',nginx);
                        } catch (error) {}
                    }
                }

            }else{
               
                try {
                    let curPath = this.MULU+DATA.id+".conf";
                    FS.unlinkSync(curPath);  
                } catch (error) {
                }
            }
            var exec = require('child_process').exec;
            exec("nginx -s reload");
            this.Xieguild();
        }

    },Jiepart:async function(ID){
        let zuhe = '@@'+ID+'@@part';
        var exec = require('child_process').exec;
        exec("ps -ef | grep "+zuhe,function(err,stdout,stderr){
            
            let fanhui = stdout.split("\n");
            for(var mm in fanhui){
               
                let tam = fanhui[mm].split(" ");
                var zuhe1 = [];
                for(var xx in tam){
                    if(tam[xx]!=""){
                        zuhe1.push(tam[xx]);
                    }
                }
               
                if(zuhe1.length > 4){
                    
                    if(zuhe1['1']  && fanhui[mm].indexOf("grep ")<=-1){
                        exec("kill -9 "+ zuhe1['1'])
                    } 
                }
            }
        });


    },Jieshell:async function(ID){

        let zuhe =  '@@'+ID+'@@shell';
        var exec = require('child_process').exec;
        exec("ps -ef | grep "+zuhe,function(err,stdout,stderr){
            let fanhui = stdout.split("\n");
            for(var mm in fanhui){
    
               let tam = fanhui[mm].split(" ");
               var zuhe1 = [];
               for(var xx in tam){
                   if(tam[xx]!=""){
                    zuhe1.push(tam[xx]);
                   }
               }

                if(zuhe1.length > 4){
                    if(zuhe1['1'] && fanhui[mm].indexOf("grep ")<=-1){
                        exec("kill -9 "+ zuhe1['1'])
                    } 
                }
            }
        });

    },Xieguild:async function(){
        let  $db = await db('host_list');
        let DATA = await $db.ZhiCha("id,type,part,off,file,shell").Select();
        if(DATA){
            let kuosfottxt = ["node "+DIR+'kuoServerLess.js @@0@@part'];
            for(var xx in DATA){
                let DATA_ = DATA[xx];
                if(DATA_.off == 1){
                    DATA_.file = Trim( Mode("Tools").GUoLV(DATA_.file),'/');
                    if(DATA_.type == 1){
                        let lujing = DIR+"HOST/"+DATA_.file+'/kuoServerLess.js @@'+DATA_.id+'@@part';
                        kuosfottxt.push("node "+lujing);
                    }
                    if(DATA_.shell != ""){
                        let jiexi =  DATA_.shell.split(",");
                        for(var ii in jiexi){
                            if(jiexi[ii] != ""){
                                let jiqu = jiexi[ii].slice(0,4);
                                if(jiqu == "node" || jiqu == "php " ){
                                    let zuihou =  str_replace('&','',Mode("Tools").GUoLV(LTrim( LTrim(LTrim(jiexi[ii],"node"),'php'),' ')));
                                    if(zuihou != ""){
                                        if(jiqu == "node"){
                                            let lujing = DIR+"HOST/"+DATA_.file+'/'+zuihou+'  @@'+DATA_.id+'@@shell';
                                            kuosfottxt.push("node "+lujing);
                                        }else{
                                            let lujing = DIR+"HOST/"+DATA_.file+'/'+zuihou+' @@'+DATA_.id+'@@shell';
                                            kuosfottxt.push("php "+lujing);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            try { 
                FS.writeFileSync( DIR+'kuosoft.txt',kuosfottxt.join("\n"));
            } catch (error) {}
        }
    }
}